package org.deri.feather.loader;

import java.io.BufferedReader;
import java.io.FileReader;

import org.deri.feather.common.IRIElement;
import org.deri.feather.common.LiteralElement;
import org.deri.feather.common.StringTools;
import org.deri.feather.common.Triple;
import org.deri.feather.indexer.Indexer;

public class NTLoader {

	Indexer indexer;
	private String namedGraphIRI;
	
	public NTLoader() {
	}
	
	/**
	 * 
	 * @param namedGraphURI
	 */
	public void setUp(String namedGraphIRI){
		indexer = new Indexer();
		indexer.setUp();
		this.namedGraphIRI = namedGraphIRI;
	}
	
	/**
	 * Load Triples from filename into Lucene.
	 * 
	 * @param filename
	 */
	public void load(String filename){
		/*
		 * 1 - Read triple from NT.
		 * 2 - Exclude the dot in the end.
		 * 3 - Separate the 3 elements <s,p,o>
		 * 4 - Create a Triple object with the 3 elements.
		 * 5 - Index the triple.
		 */
		
		System.out.println("Reading triples from " + filename);		  	
		String inputString = "";
		
		try {
			BufferedReader in = new BufferedReader(new FileReader(filename));
			long count = 0;
	  	    while ((inputString = in.readLine()) != null) {
	  	    	inputString = inputString.substring(0, inputString.lastIndexOf('.')).trim();
	  	    	
	  	    	Triple triple;
	  	    	String subject = "";
	  	    	String predicate = "";
	  	    	String object = "";
	  	    	
	  	    	subject = inputString.substring(1,inputString.indexOf("> "));
	  	    	inputString = inputString.substring(inputString.indexOf("> <")+3);
	  	    	
	  	    	predicate = inputString.substring(0,inputString.indexOf(">"));
	  	    	inputString = inputString.substring(inputString.indexOf(">")+2);
	  	    	
	  	    	object = inputString;
	  	    	if(object.startsWith("<"))
	  	    		object = object.replace("<", "").replace(">", "");
	  	    	
	  	    	if (StringTools.isURI(object))
	  	    		triple = new Triple(new IRIElement(subject), new IRIElement(predicate), 
	  	    			new IRIElement(object), new IRIElement(this.namedGraphIRI));
	  	    	else
	  	    		triple = new Triple(new IRIElement(subject), new IRIElement(predicate), 
		  	    		new LiteralElement(object), new IRIElement(this.namedGraphIRI));

	  	    	indexer.index(triple, namedGraphIRI);
	  	    	
	    		if((++count % 10000) == 0){
	    			System.out.println(count + " triples indexed");
	    			indexer.commit();
	    		}
	  	    }
	  	    indexer.close();
	  	    in.close();
	  	} catch (Exception e) {
	  		e.printStackTrace();
	  		System.out.println("Error reading data.");
	  	} 
	  	
		System.out.println("[DONE]");
	}
}
